import pygame
import sys

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH, HEIGHT = 800, 600
PADDLE_WIDTH, PADDLE_HEIGHT = 20, 100
PADDLE_SPEED = 5
PUCK_RADIUS = 10
PUCK_SPEED_X = 5
PUCK_SPEED_Y = 5
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("冰球游戏")
clock = pygame.time.Clock()

# 冰球杆类
class Paddle:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT)

    def move_up(self):
        if self.rect.top > 0:
            self.rect.y -= PADDLE_SPEED

    def move_down(self):
        if self.rect.bottom < HEIGHT:
            self.rect.y += PADDLE_SPEED

    def draw(self):
        pygame.draw.rect(screen, WHITE, self.rect)

# 冰球类
class Puck:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x - PUCK_RADIUS, y - PUCK_RADIUS, PUCK_RADIUS * 2, PUCK_RADIUS * 2)
        self.speed_x = PUCK_SPEED_X
        self.speed_y = PUCK_SPEED_Y

    def move(self):
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        # 边界碰撞检测
        if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
            self.speed_y = -self.speed_y

        # 球门碰撞检测（简单模拟得分）
        if self.rect.left <= 0:
            print("玩家 2 得分！")
            self.reset()
        elif self.rect.right >= WIDTH:
            print("玩家 1 得分！")
            self.reset()

    def reset(self):
        self.rect.x = WIDTH // 2
        self.rect.y = HEIGHT // 2
        self.speed_x = -self.speed_x

    def draw(self):
        pygame.draw.circle(screen, WHITE, (self.rect.centerx, self.rect.centery), PUCK_RADIUS)

# 创建冰球杆和冰球
paddle1 = Paddle(20, HEIGHT // 2 - PADDLE_HEIGHT // 2)
paddle2 = Paddle(WIDTH - 20 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2)
puck = Puck(WIDTH // 2, HEIGHT // 2)

# 游戏主循环
running = True
while running:
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        paddle1.move_up()
    if keys[pygame.K_s]:
        paddle1.move_down()
    if keys[pygame.K_UP]:
        paddle2.move_up()
    if keys[pygame.K_DOWN]:
        paddle2.move_down()

    # 冰球移动
    puck.move()

    # 冰球与冰球杆碰撞检测
    if puck.rect.colliderect(paddle1) or puck.rect.colliderect(paddle2):
        puck.speed_x = -puck.speed_x

    # 绘制冰球杆和冰球
    paddle1.draw()
    paddle2.draw()
    puck.draw()

    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()
sys.exit()